<?php

namespace App\Api\Dao;

use App\Models\TongUser;
use App\Models\TongUserProfit;
use Illuminate\Support\Facades\Log;

class UserProfitDao extends BaseDao
{

    /**
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder
     */
    function getBuildQuery($data)
    {
        // TODO: Implement getBuildQuery() method.
        $query = TongUserProfit::query();
        if(checkIsHasField($data,'id')){
            $query->where('id',$data['id']);
        }
        if(checkIsHasField($data,'u_id')){
            $query->where('u_id',$data['u_id']);
        }
        //流水的状态
        if(checkIsHasField($data,'type')){
            $query->where('type',$data['type']);
        }
        //收入或支出 1：收入 2支出
        if(checkIsHasField($data,'symbol')){
            $query->where('symbol',$data['symbol']);
        }
        //流水的到账状态 1：已到账 2 ：未到账
        if(checkIsHasField($data,'status')){
            $query->where('status',$data['status']);
        }
        $query->orderBy('id','desc');

        return $query;
    }

    /**
     * 获取用户的交易流水
     * @param array $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|void
     */
    public function getUserFlow(array $data)
    {
        return $this->getBuildQuery($data)->where('is_show_user',1)->where('type','!=',10)->paginate($data['pageSize']);
    }

    /**
     * 获取复购券的流水
     * @param $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getUserRepeatFlow($data){
        return $this->getBuildQuery($data)->where('type','=',10)->paginate($data['pageSize']);
    }


    /**
     * 自动更新用户的钱包余额
     * @return void
     */
    public static function autoUserMoney(){
        TongUserProfit::query()->where('symbol',1)->where('status',2)->chunk(10,function($flow){
            foreach ($flow as $item){
                $user_id = $item['u_id'];
                Log::info('更新用户钱包金额'.$user_id);
                $userInfo = TongUser::query()->where('id',$user_id)->first();
                if($item['type']!=10){
                    $pre = $userInfo['money'];
                    $next = bcadd($pre,$item['money'],2);
                    TongUser::query()->where('id',$user_id)->increment('money',$item['money']);
                }else{
                    $pre = $userInfo['repeat_money'];
                    $next = bcadd($pre,$item['money'],2);
                    //更新用户复购券
                    TongUser::query()->where('id',$user_id)->increment('repeat_money',$item['money']);
                }
                //将流水的记录修改成为已到账
                TongUserProfit::query()->where('id',$item['id'])->update(['status'=>1,'befor_money'=>$pre,'after_money'=>$next]);
            }
        });
    }
}
